<!--
 @description 经销商变更单据List
 @fileName CustomerChangeList.vue
 @author zengqiongying
 @created 2023/04/24 15:43:25
-->
<template>
  <List ref="cusList" v-model:finished="finished" :reset-fun="resetData" :load="load" :refresh="load">
    <Item
      v-for="(item, i) in list"
      :key="i"
      :item-data="item"
      @detail="toDetail(item)"
      @stop="onStop(item)"
      @edit="onEdit(item)"
    />
  </List>
</template>

<script lang="ts">
  import { ref, reactive, toRefs, defineComponent, watch, getCurrentInstance, computed } from 'vue'
  import { useRouter } from 'vue-router'
  import { useStore } from 'vuex'
  import List from '@/components/List/index.vue'
  import Item from './Item.vue'
  import { getPage, stopChange, getChangeDetail } from '@/apis/ctmCustomerChange/index'

  interface datasModle {
    list: any[]
    finished: boolean
  }
  interface anyJSONModle {
    [key: string]: any
  }
  export default defineComponent({
    name: 'CustomerChangeList',
    components: { List, Item },
    props: {
      searchValue: {
        type: String,
        default: ''
      },
      pageType: {
        type: String,
        default: '' //经销商档案调整单据类型,数据字段（CTM_CUS_ARCHIVE_CHANGE_TYPE）
      },
      type: {
        type: String,
        default: ''
      }
    },
    setup(props: any) {
      const { proxy }: any = getCurrentInstance()
      const $router = useRouter()
      const $store = useStore()
      const cusList = ref()
      const pagePaths: anyJSONModle = {
        A: 'dealerNewArchive', //经销商档案新建
        B: 'dealerNewShop', // 经销商新增门店
        C: 'dealerShopChange', // 经销商新增业务
        D: 'dealerShopChange', // 经销商取消业务
        E: 'dealerFreezeAndthaw', //经销商冻结
        F: 'dealerFreezeAndthaw', //经销商解冻
        G: 'dealerShutUpShop', //经销商分店关店
        H: 'dealerArchiveChange', //经销商档案变更
        I: 'dealerTermination' //经销商合作终止
      }
      const datas = reactive<datasModle>({
        list: [],
        finished: false
      })

      const appRoleList = computed(() => {
        // 获取当前用户的角色
        const user = $store.getters.userInfo || {}
        const roles = (user && user.appRoleDTOList) || []
        return roles.map((v: any) => v.roleName)
      })

      const defaultFilter = computed(() => {
        if (props.pageType) {
          const operator = props.pageType.indexOf(',') > 0 ? 'in' : '='
          const value = operator === 'in' ? `[${props.pageType}]` : props.pageType
          return [{ id: 'type0', property: 'type', operator, value }]
        }
        return []
      })

      const load = async (page: number, rows: number) => {
        const filtersRaw: object[] = [...defaultFilter.value]
        if (props.type === 'saved') {
          // 已保存：取数据字典 CTM_CUS_ARCHIVE_CHANGE_PROGRESS(单据进度)值为A
          filtersRaw.push({ id: 'schedule0', property: 'schedule', value: 'A', operator: '=' })
        }
        let paramsRaw = {}
        if (props.searchValue) {
          paramsRaw = {
            paramKeyword: props.searchValue
          }
        }
        const pageType = props.pageType.split(',')
        if (pageType.includes('E') || pageType.includes('F')) {
          // 当前为冻结/解冻查询时，需根据用户所属角色判断当前查询条件：
          // 当前登录用户对应角色为“CTM_客户经理角色”时，不显示提报类型为“档案科提报 B”的数据
          const ctm_a = appRoleList.value.some((name: any) => name === 'CTM-客户经理角色')
          /*  const ctm_b = appRoleList.value.some((name: any) => name === 'CTM-档案科')
          if (ctm_a || ctm_b) {            
            // 客户经理只查询提报类型为“客户经理提报 A “的数据；
            // 档案科只查询提报类型为“档案科提报 B ”的数据；
            const vals = []
            if (ctm_a) {
              vals.push('A')
            }
            if (ctm_b) {
              vals.push('B')
            }
            filtersRaw.push({
              id: 'reportType',
              property: 'reportType',
              value: vals.length === 2 ? `[${vals.join(',')}]` : vals[0],
              operator: vals.length === 2 ? `in` : '='
            })
          } */
          if (ctm_a) {
            filtersRaw.push({
              id: 'reportType',
              property: 'reportType',
              value: 'B',
              operator: '<>'
            })
          }
        }
        const paramsData = {
          page,
          rows,
          filtersRaw,
          paramsRaw: paramsRaw,
          sortersRaw: [],
          pageFlag: true
        }
        return getPage(paramsData).then((res) => {
          const resData = res.data
          const list = resData.records
          if (page === 1) {
            datas.list = list
          } else {
            datas.list = datas.list.concat(list)
          }
          if (resData.total <= datas.list.length) {
            datas.finished = true
          }
        })
      }
      const resetData = () => {
        datas.list = []
      }
      const resetPageData = () => {
        cusList.value.resetPageData()
      }
      const refreshItem = (id: string) => {
        const flag = datas.list.some((v) => v.id === id)
        if (!flag) return

        getChangeDetail(id).then((res) => {
          const d = res.data
          if (d && d.id) {
            datas.list = datas.list.map((item: any) => {
              if (item.id === id) {
                item = { ...res.data }
              }
              return item
            })
          }
        })
      }

      const toDetail = (row: any) => {
        const pathRoot = pagePaths[row.type]
        $router.push({
          path: `/${pathRoot}/detail`,
          query: {
            id: row.id
          }
        })
      }

      const onStop = (row: any) => {
        proxy.$dialog
          .confirm({
            message: '提交后将终止此变更数据，是否确认？'
          })
          .then(() => {
            const { id }: any = row
            stopChange(id).then((res: any) => {
              proxy.$toast('操作成功')
              if (props.type === 'saved') {
                datas.list = datas.list.filter((v: any) => v.id !== id)
              } else {
                refreshItem(id)
              }
            })
          })
      }

      const onEdit = (row: any) => {
        const pathRoot = pagePaths[row.type]
        $router.push({
          path: `/${pathRoot}/edit`,
          query: {
            id: row.id
          }
        })
      }
      watch(
        () => props.searchValue,
        () => {
          resetPageData()
        }
      )
      return {
        ...toRefs(datas),
        load,
        resetData,
        cusList,
        resetPageData,
        refreshItem,
        toDetail,
        onStop,
        onEdit
      }
    }
  })
</script>
<style lang="less" scoped></style>
